<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "privilege".
 *
 * @property string $id
 * @property string $pri_name
 * @property string $controller_name
 * @property string $action_name
 * @property string $created_at
 * @property string $updated_at
 * @property string $par_path
 * @property integer $level
 * @property integer $is_usable
 */
class Privilege extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'privilege';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['created_at', 'updated_at', 'is_usable'], 'integer'],
            [['pri_name', 'controller_name', 'action_name'], 'string', 'max' => 50],
            [['par_path'], 'string', 'max' => 500],
            ['par_path', 'default', 'value' => '0'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'pri_name' => '权限名称',
            'controller_name' => '控制器名称',
            'action_name' => '方法名称',
            'created_at' => '创建时间',
            'updated_at' => '修改时间',
            'par_path' => '父级',
            'is_usable' => '是否可用',
        ];
    }

    /**
     * 数据保存前
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert))
        {
            if($insert)
            {
                $this->created_at = time();
            }
            //处理权限
            $this->updated_at = time();
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 权限列表
     * @return mixed
     */
    static public function tree()
    {
        $pris = Privilege::find()
            ->where(['is_usable' => 1])
            ->select(['id', "CONCAT(par_path,'-',id) as par_path",'pri_name'])//经典
            ->orderBy('par_path')
            ->asArray()
            ->all();
        $_pris = [];
        foreach($pris as $k=>$v)
        {
            $count = count(explode('-',$v['par_path']))-2;
            $_pris[$v['par_path']] = str_repeat('-',$count).$v['pri_name'];
        }
        return $_pris;
    }
}
